/**
  * @description: 单行卡片
  * @author: hj
  * @update: hj(2020-01-14)
  */

 import React, { Component } from 'react';
 import styles from './index.module.scss';
 import { getMediaById,getVideoParams } from '@/service/Api/Chart';
 import { observer,inject,Provider } from 'mobx-react';
 import './Dplaer.css'
import "./swfobject-h5.css"
let isInitFinished = false;//视频插件是否加载完成
  
 @inject('chartStore') 
 @observer
 
 
 class CardSingle extends Component {
     constructor(props) {
         super(props);
         this.state = {
             params: [],
             data: [],
             forceFit: true, //forceFit自动试用宽度，默认false
             width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
             height: this.props.data.height ? this.props.data.height : '100%',
             condition: this.props.data.condition ? this.props.data.condition : '',
             pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
             nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
             color: this.props.data.color,
             title: '',
             chartId: this.props.data.chartId,
             id: this.props.data.componentId,
             chartData: [],
             axisArr: {},
             haveData: false,
 
             dataNull: false, // 暂无数据
 
             // 全局变量
             mainData: [], // 操作组件可操作数据
             mainName: '', // 操作组件可操作当前维度
             mainFlag: false, // 是否是操作组件
 
             pageInitFlag: true,
             affectName: '',
             requireCondition: '',
             jsession:undefined,
             devices:undefined
         };
     };
 
 
     componentWillMount() { //初始化
         const _this = this;

        const markerExtdata= window.localStorage.getItem("markerExtdata")

         
         // 预览界面
         if (_this.state.pageFlag == 'preview') {
             // 判断当前组件是否是可操作组件
             const { globalData } = _this.props.chartStore;
             if (globalData.slice().length > 0) {
                 globalData.slice().map((item,index) => {
                     if (item.affect == _this.state.chartId) { // 可操作组件
                         let affectName = item.affectDimension;
                         _this.setState({
                             mainFlag: true,
                             mainName: affectName
                         })
                     }
                 })
             }
 
             _this.interfaceRequest(_this.state.chartId,_this.state.condition);
         } else { // 配置面板
             if (_this.state.nofirst == 'nofirst') {
             } else {
             }
         }
     }
 
     // 钩子函数--组件挂载完成后
     componentDidMount() { //初始化
         this.setState({
             haveData: true
         })
     }
     // 接收父组件的数据改变
     componentWillReceiveProps = (nextProps) => {
         const _this = this;
         const { globalData, affectId } = _this.props.chartStore;
 
         // 预览界面---判断是否是变化组件
         if (nextProps.data.pageFlag == 'preview') {
             if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                 globalData.slice().map((item,index) => {
                     if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                         _this.setState({
                             pageInitFlag: false
                         })
                         let condition = {};
                         Object.keys(_this.state.requireCondition).forEach(function(keys){
                             condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                         })
                         _this.interfaceRequest(nextProps.data.chartId,condition);
                     }
                 })
             }
         }
     }
 
     // 数据接口请求
     interfaceRequest = (chartId,condition) => {
        const markerExtdata= window.localStorage.getItem("markerExtdata")
        let markerExtdataObj={}
        if (markerExtdata){
            markerExtdataObj=JSON.parse(markerExtdata)
            condition.order_id=markerExtdataObj.orderId
        }
         this.setState({
             requireCondition: condition,
         });
 
         let data = {
             charId: chartId,
             condition: condition
         };
         this.getMediaById(data);
         this.getVideoInfo(markerExtdataObj.video_url,markerExtdataObj.orderId)
     }
 
     // 数据存储刷新
     saveHandleData = () => {
         const { chartArrData } = this.props.chartStore;
         if (chartArrData.slice().length > 0) {
             chartArrData.slice().map((item) => {
                 if (item.id == this.state.chartId) {
                     this.setState({
                         haveData: false
                     },function() {
                     })
                 }
             })
         }
     }
 
 
     async getMediaById(data) {
         const res = await getMediaById(data);
         if (res.data && res.data.code === 0) {
             let str = res.data;
             if (str.data && str.data.data && str.data.data.length > 0) {
                 // 存储图例原始数据
                 const { saveChartData } = this.props.chartStore;
                 let oldData = {
                     id: this.state.chartId,
                     data: str.data.data
                 }
                 saveChartData(oldData);
                // 数据处理
                this.handleData(str.data.data);
 
             } else {
                 this.setState({
                     dataNull: true
                 })
             }
         } else {
             this.setState({
                 dataNull: true
             })
         }
     }

     getVideoInfo(url,orderId){
        getVideoParams(url,orderId).then(res=>{
            console.log("res-----------",res)
            if(res.data.code==="00000"){
                const resp=res.data.data;
                console.log("resp",resp)
                this.setState({
                    jsession:resp.jsession,
                    devices:resp.devIdNo
                },()=>{
                    this.initPlayerExample()
                })

            }
        })
     }


         /**
     * 初始化视频插件(PC网页)
     */
    initPlayerExample = () => {
        //视频插件初始化参数
        let params = {
            lang: "zh-cn" //"en", "zh-cn", "zh-tw"
        };
        //初始化flash
        if (typeof swfobject == "undefined" || swfobject.getObjectById("cmsv6flash") == null ||
            typeof swfobject.getObjectById("cmsv6flash").setWindowNum == "undefined") {
            // setTimeout(this.initFlash, 50);
        } else {
            swfobject.embedSWF("player.swf", "cmsv6flash", 600, 500, "11.0.0", null, null, params, null);
        }
        //初始化视频播放器
        ttxVideoAll.init("cmsv6flash", 720, 720, params, "auto");
        this.initFlash();
    }
    /**
     * 视频插件是否加载完成
     */
    initFlash = () => {
        if (typeof swfobject == "undefined" || swfobject.getObjectById("cmsv6flash") == null ||
            typeof swfobject.getObjectById("cmsv6flash").setWindowNum == "undefined") {
            setTimeout(this.initFlash, 50);
        } else {
            // 改变视频插件类型方法
            // swfobject.getObjectById("cmsv6flash").switchType('flash');
            //设置视频插件的语言('playerType=flash'时生效)
            swfobject.getObjectById("cmsv6flash").setLanguage("cn.xml");
            //先将全部窗口创建好
            swfobject.getObjectById("cmsv6flash").setWindowNum(4);
            //再配置当前的窗口数目
            swfobject.getObjectById("cmsv6flash").setWindowNum(4);
            //设置视频插件的服务器
            swfobject.getObjectById("cmsv6flash").setServerInfo("139.9.251.220", "6605");
            isInitFinished = true;

            //播放视频
            if (isInitFinished) {
                this.playVideo();
            }
        }
    }
    //视频插件要初始化完成后才能调用
    /**
     * 播放视频
     */
    playVideo = () => {
        //停止播放视频
        // swfobject.getObjectById("cmsv6flash").stopVideo(0);
        //设置视频窗口标题
        // swfobject.getObjectById("cmsv6flash").setVideoInfo(0, "vehicle1-CH1");
        //播放视频
        for (let index = 0; index < 4; index++) {
            swfobject.getObjectById("cmsv6flash").startVideo(index, this.state.jsession, this.state.devices, index, 1, true);
        }
        // swfobject.getObjectById("cmsv6flash").startVideo(0, this.state.jsession, "1310101", 0, 1, true);
    }
    /**
     * 停止播放视频
     */
    stopVideo = () => {
        swfobject.getObjectById("cmsv6flash").stopVideo(0);
    }
    /**
     * 重置视频窗口
     */
    reSetVideo = () => {
        swfobject.getObjectById("cmsv6flash").reSetVideo(0);
    }

 
     // 改变全局变量
     onGlobalVariable = (val) => {
         const { saveAffectId } = this.props.chartStore;
         saveAffectId(this.state.chartId);
         this.props.onGlobalVariable(val);
     }
     
     // 数据处理
     handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (storeData.affect && storeData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                storeData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (storeData.requires && storeData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                storeData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (storeData.affect &&  storeData.affect.length > 0) {
                this.setState({
                    affectName: storeData.affect[0]
                });
            }
            // 获取选择项
            if (storeData.conditionValues) {
                let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }


        let newData = [];
        if (storeData.data.length > 0) {
            newData = storeData.data.map((item,index) => {
                return item.path;
            })
            this.setState({
                dataNull: false
            })
        }

        this.setState({
            title: storeData.title,
            chartData: newData,
            haveData: true,
        })
    }
 
 
     render() {
         const _this = this;
         let Layer = this.props.layer;
 
         let cardData = _this.state.chartData;
         let widthNum = Math.floor(100 / cardData.length) + '%';
 
         return (
             <div id={this.state.id+'_'+this.state.chartId} style={{padding:"26px 14px 14px", zIndex: 99,width: this.state.width,height: this.state.height}}>
                 <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={this.state.mainData} onGlobalVariable={this.onGlobalVariable}></Layer>
                 <div className={styles.cardBox}  id={'chart_'+this.state.id+'_'+this.state.chartId} style={{height: this.state.height - 50,padding: '0 30px'}}>
                    <div className={styles.monitoring_video} id='cmsv6flash'>
                                        </div>
                     { this.state.dataNull && <p style={{height: this.state.height - 50,lineHeight: this.state.height - 50 +'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>}
                 </div>
             </div>
 
         )
     }
 
 
 }
 export default CardSingle;
 
 